package com.css.zfzx.sjcj.common.utils.cluster;

public class Bounds {

    public Point sw;
    public Point ne;

    public Bounds (Point sw, Point ne) {
        this.sw = sw;
        this.ne = ne;
    }

    public boolean containsPoint (Point point) {
        Point sw = this.sw;
        Point ne = this.ne;
        return (point.lng >= sw.lng && point.lng <= ne.lng && point.lat >= sw.lat && point.lat <= ne.lat);
    }

    public Bounds getExtendedBounds (float gridSize, int zoom){
        Bounds bounds = this.cutBoundsInRange();
        Pixel pixelNE = PointToPixelUtil.pointToPixel(bounds.ne, zoom);
        Pixel pixelSW = PointToPixelUtil.pointToPixel(bounds.sw, zoom);
        pixelNE.x += gridSize;
        pixelNE.y -= gridSize;
        pixelSW.x -= gridSize;
        pixelSW.y += gridSize;
        Point newNE = PointToPixelUtil.pixelToPoint(pixelNE, zoom);
        Point newSW = PointToPixelUtil.pixelToPoint(pixelSW, zoom);
        return new Bounds(newSW, newNE);
    };

    private Bounds cutBoundsInRange () {
        double maxX = getRange(this.ne.lng, -180, 180);
        double minX = getRange(this.sw.lng, -180, 180);
        double maxY = getRange(this.ne.lat, -74, 74);
        double minY = getRange(this.sw.lat, -74, 74);
        return new Bounds(new Point(minX, minY), new Point(maxX, maxY));
    };

    /**
     * 对单个值进行边界处理。
     * @param {Number} i 要处理的数值
     * @param {Number} min 下边界值
     * @param {Number} max 上边界值
     *
     * @return {Number} 返回不越界的数值
     */
    private double getRange (double i, double mix, double max) {
        if (mix != 0) i = Math.max(i, mix);
        if (max != 0) i = Math.min(i, max);
        return i;
    }

    public static void main(String[] args) {
        //116.27827,39.84677;116.53713,39.95212
        //112.15613259541988,36.68362383971367;120.65926740458013,42.9711910525869
        Point sw = new Point(116.27827,39.84677);
        Point ne = new Point(116.53713,39.95212);
        Bounds bounds = new Bounds(sw, ne);
        int gridSize = 6, zoom = 12;
        Bounds bds = bounds.getExtendedBounds(gridSize, zoom);
        System.out.println(bds.sw.lng + "," + bds.sw.lat + ";" + bds.ne.lng + "," + bds.ne.lat);
    }

}
